package org.rc.config;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import javax.servlet.http.HttpSession;
import javax.websocket.HandshakeResponse;
import javax.websocket.server.HandshakeRequest;
import javax.websocket.server.ServerEndpointConfig;

public class WsSessionConfig extends ServerEndpointConfig.Configurator implements ApplicationContextAware {
    private static volatile BeanFactory context;

    public void modifyHandshake(ServerEndpointConfig sec, HandshakeRequest request, HandshakeResponse response) {
        HttpSession httpSession = (HttpSession) request.getHttpSession();
        if (null != httpSession) {
            sec.getUserProperties().put(HttpSession.class.getName(), httpSession);
            sec.getUserProperties().put("clientIp", httpSession.getAttribute("remoteHost"));
        }
        super.modifyHandshake(sec, request, response);
    }

    public <T> T getEndpointInstance(Class<T> clazz) throws InstantiationException {
        return (T) context.getBean(clazz);
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = (BeanFactory) applicationContext;
    }
}
